package com.smart.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.smart.model.News;
import com.smart.model.NewsMessage;
import com.smart.model.TextMessage;
import com.thoughtworks.xstream.XStream;



public class MessageUtil {
	/**
	 * 
	 * @param req
	 * @return
	 * @throws IOException
	 * @throws DocumentException
	 */
   public static Map<String,String> xmlToMap(HttpServletRequest req) throws IOException, DocumentException
   {
	   Map<String,String> map=new HashMap<String,String>();
	   SAXReader reader=new SAXReader();
	   InputStream ins=req.getInputStream();
	   
	   Document doc=reader.read(ins);
	   
	   Element root=doc.getRootElement();
	   List<Element> list=root.elements();
	   
	   for(Element e:list)
	   {
		map.put(e.getName(), e.getText()); 
	   }	
	   ins.close();
	   return map;
   }
   
   /**
    * ���ı���Ϣ����ת��Ϊxml
    * @param textMessage
    * @return
    */
   public static String textMessageToXml(TextMessage textMessage)
   {
	   XStream xstream=new XStream();
	   xstream.alias("xml",textMessage.getClass());
	   return xstream.toXML(textMessage);
   }
   
   /**
    * ͼ����Ϣת��Ϊxml
    * @param newsMessage
    * @return
    */
   public static String newsMessageToXml(NewsMessage newsMessage)
   {
	   XStream xstream=new XStream();
	   xstream.alias("xml",newsMessage.getClass());
	   xstream.alias("item",new News().getClass());
	   return xstream.toXML(newsMessage);
   }
   
   
   /**
    * ͼ����Ϣ����װ
    * @param toUserName
    * @param fromUserName
    * @return
    */
   public static String initMessgae(String toUserName,String fromUserName)
   {
	   String message=null;
	   List<News> newsList=new ArrayList<News>();
	   News news=new News();
	   news.setTitle("title");
	   news.setDescription("description");
	   news.setPicUrl("");
	   news.setUrl("");
	   newsList.add(news);
	   
	   NewsMessage newsMessage=new NewsMessage();
	   newsMessage.setFromUserName(toUserName);
	   newsMessage.setToUserName(fromUserName);
	   newsMessage.setCreateTime(String.valueOf(new Date().getTime()));
	   newsMessage.setMsgType("news");
	   newsMessage.setArticles(newsList);
	   newsMessage.setArticleCount(newsList.size());
	   message=MessageUtil.newsMessageToXml(newsMessage);
	   return  message;
   } 
}

